﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using BayesClassifier;

namespace grounding.parser.Parsers
{
    public class NaiveBayesParser : IParser
    {
        protected Classifier nbClassifier = new Classifier();

        /// <summary>
        /// Creates and trains a Naive Bayes classifier
        /// </summary>
        /// <param name="trainingFilesDirectory">Directory where the training sentences are located</param>
        public NaiveBayesParser(string trainingFilesDirectory)
        {
            foreach (string file in Directory.GetFiles(trainingFilesDirectory))
            {
                // Remove folders in path and remove extension
                string name = file.Split(new char[] { '\\' }).Last().Split(new char[] { '.' }).First().Replace("_", "");
                try
                {
                    nbClassifier.TeachCategory(Label.GetLabel(name).Element, new StreamReader(file));
                }
                catch(ArgumentException)
                {
                    // Ignore files that don't match
                    Console.WriteLine("Ignoring file with name {0} while training nbClassifier", name);
                }
            }
        }

        #region IParser Members

        public ILogicElement Parse(string naturalText) { double temp; return Parse(naturalText, out temp); }
        public ILogicElement Parse(string naturalText, out double confidence)
        {
            Dictionary<string, double> score = nbClassifier.Classify(new StringReader(naturalText));

            // Select maximum likelihood classification using super fancy LINQ with lambda functions
            KeyValuePair<string, double> best = score.Aggregate((l, r) => l.Value > r.Value ? l : r);
            confidence = best.Value;
            return Label.GetLabel(best.Key);
        }

        #endregion
    }
}
